package com.laikan.reader.bookstart.activity;

import android.app.TabActivity;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.graphics.Color;
import android.graphics.drawable.BitmapDrawable;
import android.graphics.drawable.Drawable;
import android.os.Bundle;
import android.os.Handler;
import android.text.TextUtils;
import android.util.DisplayMetrics;
import android.view.KeyEvent;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.ViewTreeObserver;
import android.view.ViewTreeObserver.OnGlobalLayoutListener;
import android.view.Window;
import android.widget.*;
import android.widget.RadioGroup.OnCheckedChangeListener;
import com.laikan.library.components.BasicApplication;
import com.laikan.library.helpers.BasicEvent;
import com.laikan.library.utils.DeviceUtil;
import com.laikan.library.utils.SPUtil;
import com.laikan.reader.R;
import com.laikan.reader.apirequester.UpdateUtil;
import com.laikan.reader.bookfriend.activity.PersonalActivity;
import com.laikan.reader.bookshelf.activity.BookShelfActivity;
import com.laikan.reader.bookstore.activity.BookStoreActivity;
import com.laikan.reader.core.LaikanApplication;
import com.laikan.reader.core.bean.BaseDataBean;
import com.laikan.reader.core.events.HomeTabEvent;
import com.laikan.reader.core.events.LaiKanEvent;
import com.laikan.reader.core.utils.ActivityUitl;
import com.laikan.reader.core.utils.PublicUtil;
import com.laikan.reader.core.utils.SystemUtil;
import com.umeng.analytics.MobclickAgent;
import org.greenrobot.eventbus.EventBus;
import org.greenrobot.eventbus.Subscribe;

import java.text.ParseException;
import java.text.SimpleDateFormat;

import static com.laikan.reader.core.events.LaiKanEvent.EVENT_ID_RET_DOT_GONE;
import static com.laikan.reader.core.events.LaiKanEvent.EVENT_ID_RET_DOT_VISIBLE;

/**
 * @author wx
 * @category 主页面
 */
public class HomeActivity extends TabActivity {
    private static final int RADIO_BOOKSHELF_TAB = 0;
    private static final int RADIO_BOOKSTORE_TAB = 1;
//    private static final int RADIO_BOOKFOCUS_TAB = 2;
    private static final int RADIO_BOOKMYSELF_TAB = 2;

    private int screenWidth;
    private int screenHeight;
    private int width, height; //图片宽高
    private float density;
    private static TabHost tabhost;
    private static RadioGroup group;
    BaseDataBean result = new BaseDataBean();
    private String TAG = "TableHost";
    private RadioButton radioBtn;
    private RadioButton radio_bookshelf, radio_bookstore, radio_bookfocus, radio_bookmyself;
    private String bookid;
    private ImageView mine_red_point;
    OnCheckedChangeListener checkedChangeListen = new OnCheckedChangeListener() {
        public void onCheckedChanged(RadioGroup group, int checkedId) {

            int toX = radioBtn.getWidth();

            switch (checkedId) {
                case R.id.radio_bookshelf:
//                    MobclickAgent.onEvent(HomeActivity.this, "bottom_bookshelf");
                    MobclickAgent.onEvent(HomeActivity.this, "sj-sy");//书架-首页
                    tabhost.setCurrentTab(RADIO_BOOKSHELF_TAB);
                    resetTabIcon(RADIO_BOOKSHELF_TAB);
                    break;
                case R.id.radio_bookstore:
//                    MobclickAgent.onEvent(HomeActivity.this, "bottom_selection");
                    MobclickAgent.onEvent(HomeActivity.this, "jx-sy");//精选-首页
                    tabhost.setCurrentTab(RADIO_BOOKSTORE_TAB);
                    resetTabIcon(RADIO_BOOKSTORE_TAB);
                    break;
//                case R.id.radio_bookfocus:
//                    MobclickAgent.onEvent(HomeActivity.this, "kd-sy");//精选-首页
//                    tabhost.setCurrentTab(RADIO_BOOKFOCUS_TAB);
//                    resetTabIcon(RADIO_BOOKFOCUS_TAB);
//                    break;
                case R.id.radio_bookmyself:
                    MobclickAgent.onEvent(HomeActivity.this, "bottom_mybookshelf");
                    tabhost.setCurrentTab(RADIO_BOOKMYSELF_TAB);
                    resetTabIcon(RADIO_BOOKMYSELF_TAB);
                    // mine_red_point.setVisibility(View.GONE);
                    // SPUtil.putBoolean("show_mine_point",false);

                    break;
                default:
                    break;
            }
        }
    };
    private MyBroadcast broadcast;
    private View direct_view;
    private ImageView direct_image, iv_book_del, iv_bookshelf, iv_bookstore, iv_bookfocus, iv_bookmyself;
    private String change_position_tab;
    private long mkeyTime;
    private RelativeLayout mLayout_Bottom;
    private RelativeLayout rl_delete_layout;
    private Drawable iv_delete_drawable;
    public int currentTab = 0;
    private String messageVersion;
    private TextView mTvButtom_Del;

    public static void setCheckById(int resourceid, int currentTabIndex) {
        tabhost.setCurrentTab(currentTabIndex);
        group.check(resourceid);
    }

    @SuppressWarnings ("deprecation")
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        requestWindowFeature(Window.FEATURE_NO_TITLE);
        setContentView(R.layout.main_tab);
        tabhost = this.getTabHost();
        LaikanApplication.disPlay = getWindowManager().getDefaultDisplay();
        mine_red_point = (ImageView)findViewById(R.id.mine_red_point);

        // 获取屏幕宽高
        DisplayMetrics dm = new DisplayMetrics();
        getWindowManager().getDefaultDisplay().getMetrics(dm);
        density = dm.density; //屏幕的密度(像素比例)
        int densityDip = dm.densityDpi; //屏幕密度（每寸像素）
        screenWidth = dm.widthPixels;
        screenHeight = dm.heightPixels;
        init();
        broadcast = new MyBroadcast();
        initView();
        if (ActivityUitl.isNetworkAvailable(getApplicationContext())) {
            //检查更新版本
            new Handler().post(new Runnable() {

                @Override
                public void run() {
                    UpdateUtil.checkVersion(HomeActivity.this, false);
                }
            });

        }
//        else {
//            ToastMgr.showShortToast(R.string.laikan_network_anomaly);
//        }

        if(getIntent() != null && "login_custom".equals(getIntent().getStringExtra("login_type"))){
            tabhost.setCurrentTab(RADIO_BOOKSTORE_TAB);
            group.check(R.id.radio_bookstore);
        }else {
            tabhost.setCurrentTab(RADIO_BOOKSHELF_TAB);
            group.check(R.id.radio_bookshelf);
        }
//        if(LaikanApplication.getHomeOptions()==bookfocus){
//            tabhost.setCurrentTab(RADIO_BOOKFOCUS_TAB);
//            group.check(R.id.radio_bookfocus);
//        }

        SPUtil.putBoolean("refresh_tab", false);
        EventBus.getDefault().register(this);
    }

    private void init() {
        radio_bookshelf = (RadioButton)findViewById(R.id.radio_bookshelf);
        radio_bookstore = (RadioButton)findViewById(R.id.radio_bookstore);
//        radio_bookfocus = (RadioButton)findViewById(R.id.radio_bookfocus);
        radio_bookmyself = (RadioButton)findViewById(R.id.radio_bookmyself);
        iv_bookshelf = (ImageView)findViewById(R.id.iv_bookshelf);
        iv_bookstore = (ImageView)findViewById(R.id.iv_bookstore);
//        iv_bookfocus = (ImageView)findViewById(R.id.iv_bookfocus);
        iv_bookmyself = (ImageView)findViewById(R.id.iv_bookmyself);

        group = (RadioGroup)findViewById(R.id.radioGroup1);
        group.setOnCheckedChangeListener(checkedChangeListen);
        Intent first = new Intent(this, BookShelfActivity.class);
        Intent second = new Intent(this, BookStoreActivity.class);
//        Intent third = new Intent(this, BookFocusActivity.class);
        Intent fourth = new Intent(this, PersonalActivity.class);

        tabhost.addTab(tabhost.newTabSpec("tab1").setIndicator("tab1", null).setContent(first));
        tabhost.addTab(tabhost.newTabSpec("tab2").setIndicator("tab2", null).setContent(second));
//        tabhost.addTab(tabhost.newTabSpec("tab3").setIndicator("tab3", null).setContent(third));
        tabhost.addTab(tabhost.newTabSpec("tab4").setIndicator("tab4", null).setContent(fourth));

        radioBtn = (RadioButton)findViewById(R.id.radio_bookstore);
        ViewTreeObserver vto2 = radioBtn.getViewTreeObserver();
        vto2.addOnGlobalLayoutListener(new OnGlobalLayoutListener() {
            @Override
            public void onGlobalLayout() {
                radioBtn.getViewTreeObserver().removeGlobalOnLayoutListener(this);
            }
        });
    }

    private void resetTabIcon(int position) {
        switch (position) {
            case RADIO_BOOKSHELF_TAB:
                iv_bookshelf.setImageResource(R.drawable.lk_bookshelf_checked);
                iv_bookstore.setImageResource(R.drawable.lk_rack_unchecked);
//                iv_bookfocus.setImageResource(R.drawable.bookfocus_unselect);
                iv_bookmyself.setImageResource(R.drawable.lk_personal_unchecked);
                break;
            case RADIO_BOOKSTORE_TAB:
                iv_bookshelf.setImageResource(R.drawable.lk_bookshelf_unchecked);
                iv_bookstore.setImageResource(R.drawable.lk_rack_checked);
//                iv_bookfocus.setImageResource(R.drawable.bookfocus_unselect);
                iv_bookmyself.setImageResource(R.drawable.lk_personal_unchecked);
                break;
//            case RADIO_BOOKFOCUS_TAB:
//                iv_bookshelf.setImageResource(R.drawable.lk_bookshelf_unchecked);
//                iv_bookstore.setImageResource(R.drawable.lk_rack_unchecked);
//                iv_bookfocus.setImageResource(R.drawable.bookfocus_select);
//                iv_bookmyself.setImageResource(R.drawable.lk_personal_unchecked);
//                break;
            case RADIO_BOOKMYSELF_TAB:
                iv_bookshelf.setImageResource(R.drawable.lk_bookshelf_unchecked);
                iv_bookstore.setImageResource(R.drawable.lk_rack_unchecked);
//                iv_bookfocus.setImageResource(R.drawable.bookfocus_unselect);
                iv_bookmyself.setImageResource(R.drawable.lk_personal_checked);
                break;
            default:
                break;

        }
    }
    /**
     * event 解析
     *
     * @param event
     */
    @Subscribe
    public void onEvent(BasicEvent event) {
        switch (event.getEventID()) {
            case EVENT_ID_RET_DOT_VISIBLE: //红点显示
                mine_red_point.setVisibility(View.VISIBLE);
                break;
            case EVENT_ID_RET_DOT_GONE: // 红点隐藏
                mine_red_point.setVisibility(View.GONE);
                break;
        }

    }

    @Override
    protected void onResume() {
        super.onResume();
        MobclickAgent.onResume(this);

        bookid = getIntent().getStringExtra("bookId");
        if (!TextUtils.isEmpty(bookid)) {
            // 如果bookid不为空，跳转到书架
            tabhost.setCurrentTab(RADIO_BOOKSHELF_TAB);
            group.check(R.id.radio_bookshelf);
        }
        //        if(SPUtil.getBoolean("show_mine_point",true)){//设置默认为true
        //            mine_red_point.setVisibility(View.VISIBLE);
        //        }else{
        //            mine_red_point.setVisibility(View.GONE);
        //        }
        SystemUtil.checkRedDotShow();
    }

    @Override
    protected void onPause() {
        super.onPause();
        MobclickAgent.onPause(this);
        //        unregisterReceiver(broadcast);
    }

    @Override
    public boolean onKeyDown(int keyCode, KeyEvent event) {
        // 2秒内连续按两次 退出程序
        if (keyCode == KeyEvent.KEYCODE_BACK) {
            if ((System.currentTimeMillis() - mkeyTime) > 2000) {
                mkeyTime = System.currentTimeMillis();
                Toast.makeText(this, R.string.personal_exit_program, Toast.LENGTH_SHORT).show();
            }else {
                finish();
            }
            return true;
        }
        return super.onKeyDown(keyCode, event);
    }

    /**
     * 设置指导页面的显示和隐藏
     *
     * @param flag
     */
    public void setDirection(boolean flag) {
        if (flag) {
            direct_view.setVisibility(View.GONE);
            direct_image.setVisibility(View.GONE);
        }else {
            direct_view.setVisibility(View.GONE);
            direct_image.setVisibility(View.GONE);
        }
    }


    private void initView() {
        direct_view = findViewById(R.id.direct_view);
        direct_image = (ImageView)findViewById(R.id.direct_image);

        mLayout_Bottom = (RelativeLayout)findViewById(R.id.layout_bottom);
        rl_delete_layout = (RelativeLayout)findViewById(R.id.rl_del);
        mTvButtom_Del = (TextView)findViewById(R.id.tv_buttom_del);
        iv_delete_drawable = new BitmapDrawable(PublicUtil.getAlphaBitmap(PublicUtil.readBitMap(this, R.drawable.lk_book_del), Color.parseColor("#ffffff")));
        iv_book_del = (ImageView)findViewById(R.id.iv_book_del);
        iv_book_del.setImageDrawable(iv_delete_drawable);
        rl_delete_layout.setVisibility(View.GONE);
        rl_delete_layout.setOnClickListener(new OnClickListener() {
            @Override
            public void onClick(View view) {

                LaiKanEvent event = LaiKanEvent.getInstance();
                event.setEventID(LaiKanEvent.EVENT_ID_BOOK_DELETE_CACHE);
                if (currentTab == 0) {
                    event.setEventAction("from_shlf");
                }else {
                    event.setEventAction("from_history");
                }
                BasicApplication.postEvent(event);
            }
        });

        direct_view.setOnClickListener(new OnClickListener() {

            @Override
            public void onClick(View v) {
                SPUtil.putBoolean("lk_direct", false);
                setDirection(false);
            }
        });

        direct_image.setOnClickListener(new OnClickListener() {

            @Override
            public void onClick(View v) {
                SPUtil.putBoolean("lk_direct", false);
                setDirection(false);
            }
        });
    }

    /**
     * 将 yyyy-MM-dd HH:mm:ss 该格式的时间转换成毫秒
     *
     * @param time
     *
     * @return 毫秒
     */
    private long convertTime(String time) {
        SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
        try {
            return sdf.parse(time).getTime();
        }catch (ParseException e) {
            e.printStackTrace();
        }
        return 0l;
    }

    class MyBroadcast extends BroadcastReceiver {

        @Override
        public void onReceive(Context context, Intent intent) {
            int position = intent.getIntExtra("position", 0);
            tabhost.setCurrentTab(position);
            switch (position) {
                case RADIO_BOOKSHELF_TAB:
                    group.check(R.id.radio_bookshelf);
                    break;
                case RADIO_BOOKSTORE_TAB:
                    group.check(R.id.radio_bookstore);
                    break;
//                case RADIO_BOOKFOCUS_TAB:
//                    group.check(R.id.radio_bookfocus);
//                    break;
                case RADIO_BOOKMYSELF_TAB:
                    group.check(R.id.radio_bookmyself);
                    break;
                default:
                    break;
            }
        }
    }

    @Subscribe
    public void onEventMainThread(HomeTabEvent event) {
        if (event != null) {
            if (event.mIsCoverHomeTab == 0) {
                rl_delete_layout.setVisibility(View.VISIBLE);
                changeBookSelectRecord(0);
            }else if (event.mIsCoverHomeTab == 1) {
                rl_delete_layout.setVisibility(View.GONE);
                changeBookSelectRecord(0);
            }else if(rl_delete_layout.getVisibility() == View.VISIBLE && event.mIsCoverHomeTab == 2){
                changeBookSelectRecord(event.RefreshBookDelCount);
            }
        }
    }

    /**
     * 更新已选择的历史记录数量
     *
          * @param recordNum
     */
        private void changeBookSelectRecord(int recordNum) {
            mTvButtom_Del.setText(DeviceUtil.getHtmlFormatedString(HomeActivity.this, R.string.book_has_selected, recordNum));
        }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        EventBus.getDefault().unregister(this);
    }
}